package com.syq.day1;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;

/**
 * @author syq
 * 函数对象好处2：延迟执行
 */
public class Sample5 {
    static Logger logger = init(Level.INFO);
    public static void main(String[] args) {
        // logger级别不是debug时，expensive() 也会被执行，只是 logger.debug不会打印东西
//        logger.debug("{}",expensive());
        if (logger.isDebugEnabled()){
            logger.debug("{}",expensive());// void debug(String message, Object p0);
        }

        // void debug(String message, Supplier<?>... paramSuppliers); Supplier 有个get方法，无参且有返回值
        // 使用这个形参的debug方法，源码会判断 logger的日志级别是否是 debugger
        logger.debug("{}",() -> expensive());
    }

    static String expensive(){
        System.out.println("expensive 被执行了");
        return "expensive日志";
    }


    static Logger init(Level level){
        // 创建配置构建器
        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder()
                .setStatusLevel(Level.ERROR)
                .setConfigurationName("BuilderTest");

        AppenderComponentBuilder appender = builder.newAppender("Console", "CONSOLE")
                .add(builder.newLayout("PatternLayout")
                        .addAttribute("pattern", "%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %m%n"));
        builder.add(appender)
                .add(builder.newRootLogger(level).add(builder.newAppenderRef("Console")));
        // 应用配置
        Configurator.initialize(builder.build());
        return LogManager.getLogger();
    }
}
